if(!window.mc){
	window.mc = function(){};
}
mc.template = {
	init: function(path,v){
		this.path = path.replace(/\/$/,"") + "/";
		if(v){
			this.v = "?v="+v;
		}
	},
	v: "",
	path: "",
	has: {},
	ready: {},
	re: /<\?template\s+name=\"([^"]+)\"\s*\?>([\S\s]*?)<\?\/template\?>/g,
	load: function(name,cb){
		if(!this.has[name]){
			this.has[name] = $.Deferred();
			if(cb){
				this.has[name].done(cb);
			}
			$.ajax({
				context: {
					re:this.re,
					ready: this.ready,
					has: this.has,
					name: name,
					full_name: this.path + name + ".html" + this.v
				},
				url: this.path + name + ".html"+this.v,
				dataType: "text",
				success: this._success,
				error: this._error
			});
			return true;
		}else if(cb){
			this.has[name].done(cb);
			return true;
		}else{
			return false;
		}
	},
	_error: function(a){

		//$.ajax({
		//	context: this,
		//	url: mc.template.path + this.name + ".html"+mc.template.v,
		//	dataType: "text",
		//	success: mc.template._success,
		//	error: mc.template._error
		//});
		window.dbg("Error("+a.status+") loading '" + this.full_name + "'");
		//alert("Error("+a.status+") loading '" + this.full_name + "'");
		
	},
	_success: function(text) {
		var t;
		while((t = this.re.exec(text))){
			this.ready[t[1]] = true;
			$.template(t[1],t[2]);
		}
		this.has[this.name].resolve();
	},
	isready: function(name){
		return this.ready[name];
	},
	process: function(name,data,to,cb){
		var ary = name.split(".");
		var file = ary[0];
		var tmpl = ary[1] || file;
		this.load(file,function(){
			var root = $.tmpl(tmpl,data).appendTo(to);
			if(window[file] && typeof(window[file]) == "function"){
				window[file](root);
			}
			if(cb){
				cb();
			}
		});
	},
	load_header: function(name,cb){
		this.process(name,this,"head",cb);
	}
};
